// 订阅者

// watcher目录
import Dep from "./dep";

let $uid = 0;
export default class Watcher {
    constructor(exp, scope, cb) {
        this.exp = exp;
        this.scope = scope;
        this.cb = cb;
        this.uid = $uid++;
        this.update();
    }

    /**
     * 计算表达式, 获取插值表达式最新值
     */
    get() {
        // Dep.target之所以更改是为了使Dep.target永远指向当前的Watcher
        Dep.target = this;
        let newValue = Watcher.computeExpression(this.exp, this.scope);
        // console.log(newValue);
        Dep.target = null;
        return newValue;
    }

    /**
     * 完成回调函数的调用
     */
    update() {
        let newValue = this.get();
        // console.log("update",newValue);
        this.cb && this.cb(newValue)
    }

    /**
     * 计算插值表达式的最新值
     * @param exp
     * @param scope
     * @returns {*}
     */
    static computeExpression(exp, scope) {
        // console.log('computeExpression==>');
        // 创建函数
        // 把scope当做作用域
        // 函数内部使用with来指定作用域
        // 执行函数,得到表达式的值
        // console.log("exp: ", exp);
        let fn = new Function("scope", "with(scope){return " + exp + "}");
        return fn(scope);
    }
}
